package impl

import (
	"context"
	"errors"
	admin "gitee.com/kordar/goadmin/admin/form"
	model "gitee.com/kordar/goadmin/admin/models"
	"gitee.com/kordar/goadmin/admin/service"
	"gitee.com/kordar/goadmin/admin/vo"
	"gitee.com/kordar/goadmin/reader"
	"github.com/kordar/ginsys/resource"
	"github.com/kordar/ginsys/resp"
	"github.com/kordar/gocrud"
	gocrudgorm "github.com/kordar/gocrud-gorm"
	"gorm.io/gorm"
)

type RouterServiceImpl struct {
	db *gorm.DB
	gocrud.CommonResourceService
	dictService service.DictService
}

func NewRouterService(db *gorm.DB, dictService service.DictService) *RouterServiceImpl {
	return &RouterServiceImpl{db: db, dictService: dictService}
}

func (service RouterServiceImpl) ResourceName() string {
	return "router"
}

func (service RouterServiceImpl) Search(body gocrud.SearchBody) gocrud.SearchVO {
	searchBody := gocrudgorm.NewGormSearchBody(body)
	db := searchBody.GormQuery(service.db, nil).Model(&model.SysRouter{})
	queryReader := reader.NewQueryReader(db, int(body.Page), int(body.PageSize))
	var data []*vo.SysRouterVO
	return queryReader.SearchVO(&data, nil)
}

func (service RouterServiceImpl) Remove(body gocrud.RemoveBody) error {
	return body.Delete(&model.SysRouter{}, service.db, nil)
}

func (service RouterServiceImpl) Update(body gocrud.FormBody) (interface{}, error) {
	return body.Update(&model.SysRouter{}, service.db.Select("Name", "URL", "Type", "Data"), nil)
}

func (service RouterServiceImpl) Create(body gocrud.FormBody) (interface{}, error) {
	return resource.Create(body, service.db.Select("Name", "URL", "Type", "Data"), &admin.SysRouterForm{}, nil, func(v interface{}) error {
		sysRouter := v.(*model.SysRouter)
		if service.db.Where("name = ?", sysRouter.Name).First(sysRouter).Error == nil {
			return errors.New("router name has exists")
		}
		return nil
	})
}

func (service RouterServiceImpl) Configs(ctx context.Context) map[string]interface{} {
	locale := resp.GetLocale(ctx)
	return map[string]interface{}{
		"router-type": service.dictService.Options("configs.router-type", locale),
	}
}
